package mylib

// 基础包
import (
	"fmt"
	"path"
	"strconv"

	"github.com/henrylee2cn/pholcus/app/downloader/request" //必需
	. "github.com/henrylee2cn/pholcus/app/spider"           //必需
	"github.com/henrylee2cn/pholcus/common/goquery"         //DOM解析
)

func init() {
	LoroPiana.Register()
}

type news struct {
	module string //模块
	title  string //标题
	href   string //连接
	top    string
}

var LoroPiana = &Spider{
	Name:        "链家租房",	
	Description: "房产照片下载",
	// Pausetime: 300,
	// Keyin:   KEYIN,
	// Limit:        LIMIT,
	EnableCookie: false,

	RuleTree: &RuleTree{
		Root: func(ctx *Context) {
			ctx.AddQueue(&request.Request{
				Method: "GET",
				Url:    "https://bj.lianjia.com/",
				Rule:   "城市列表",
			})
		},

		Trunk: map[string]*Rule{
			"城市列表": {
				ParseFunc: func(ctx *Context) {
					fmt.Println("城市列表")

					dom := ctx.GetDom()
					city_list := dom.Find(".city-enum.fl a")

					city_list.Each(func(i int, s *goquery.Selection) {
						url, ok := s.Attr("href")
						if ok {
							ctx.AddQueue(&request.Request{
								Url:  url + "zufang", //https://bj.lianjia.com/
								Rule: "分类列表",
							})
						}
					})
				},
			},

			"分类列表": {
				ParseFunc: func(ctx *Context) {

					for i := 1; i <= 100; i++ {
						//for i := 1; i <= 2; i++ {
						//fmt.Println(i)
						url := ctx.GetUrl() + "/zufang/pg" + strconv.Itoa(i)
						ctx.AddQueue(&request.Request{
							Url:  url,
							Rule: "房产列表",
						})
					}
				},
			},
			"房产列表": {
				// ItemFields: []string{
				// 	"标题",
				// 	"价格",
				// 	"链接",
				// },
				ParseFunc: func(ctx *Context) {
					dom := ctx.GetDom()
					item_list := dom.Find(".house-lst li")

					item_list.Each(func(i int, s *goquery.Selection) {
						house_href, ok := s.Find("a").Attr("href")
						if ok {
							// ctx.Output(map[int]interface{}{
							// 	0: house_title,
							// 	1: price,
							// 	2: house_href,
							// })
							ctx.AddQueue(&request.Request{
								Url:  house_href,
								Rule: "房屋信息",
							})
						}

					})
				},
			},

			"房屋信息": {
				ParseFunc: func(ctx *Context) {
					//fmt.Println("房屋信息")
					dom := ctx.GetDom()
					guide_map := dom.Find(".thumbnail li")

					guide_map.Each(func(i int, s *goquery.Selection) {
						data_src, ok := s.Find("img").Attr("src")
						if ok {
							dir, ok := s.Attr("data-desc")
							if !ok {
								dir = "未知"
							}
							ctx.AddQueue(&request.Request{
								Url:  data_src,
								Rule: "图片地址",
								Temp: map[string]interface{}{
									"dir": dir,
								},
							})
						}
					})
				},
			},
			"图片地址": {
				ParseFunc: func(ctx *Context) {

					_, baseName := path.Split(ctx.GetUrl())

					dir := ctx.GetTemp("dir", "").(string)
					//fmt.Println(baseName, dir)

					ctx.FileOutput(dir + "/" + baseName)
				},
			},
		},
	},
}
